package com.story.modular.app.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.story.common.constant.factory.PageFactory;
import com.story.common.exception.BizExceptionEnum;
import com.story.common.exception.BussinessException;
import com.story.common.persistence.dao.ChannelItemMapper;
import com.story.common.persistence.dao.ChannelMapper;
import com.story.common.persistence.dao.VedioDetailMapper;
import com.story.common.persistence.model.Channel;
import com.story.common.persistence.model.ChannelItem;
import com.story.common.persistence.model.VedioDetail;
import com.story.config.properties.UpyunProperties;
import com.story.core.base.controller.BaseController;
import com.story.core.util.ToolUtil;
import com.story.modular.app.dao.ChannelItemDao;
import com.story.modular.app.dao.VedioCategoryDao;
import com.story.modular.app.dao.VedioDetailDao;
import com.story.modular.app.transfer.ChannelRadioDto;
import com.story.modular.app.warpper.VedioWarpper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.constraints.NotNull;
import java.util.*;

/**
 * @author yangbo
 * @date 2019-08-07 11:17
 */
@Controller
@RequestMapping(value = "/channel/item")
public class ChannelItemController extends BaseController {

    public static final String PREFIX = "/app/channel/item/";

    @Autowired
    private ChannelItemDao channelItemDao;

    @Autowired
    private VedioCategoryDao vedioCategoryDao;

    @Autowired
    private UpyunProperties upyunProperties;

    @Autowired
    private ChannelItemMapper channelItemMapper;

    @Autowired
    private ChannelMapper channelMapper;

    @Autowired
    private VedioDetailDao vedioDetailDao;

    /**
     * 首页
     * @return
     */
    @RequestMapping(value = "")
    public String index() {
        return PREFIX + "channel_item.html";
    }

    /**
     * 频道资源列表
     * @param keyword
     * @return
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(@RequestParam(value = "keyword",required = false) String keyword) {
        Page<VedioDetail> page = new PageFactory<VedioDetail>().defaultPage();
        if(StringUtils.isNotBlank(keyword)) {
            keyword = keyword.trim();
        }
        List<Map<String,Object>> channelResourceList = channelItemDao.getChannelRadioList(page, keyword,
                page.getOrderByField(), page.isAsc());
        List<Map<String,Object>> result = new ArrayList<>();
        for (Map map : channelResourceList) {
            if(StringUtils.isNotBlank((String)map.get("cateName"))) {
                String[] cateNames = ((String)map.get("cateName")).split(",");
                Integer[] cateNameInts = new Integer[cateNames.length + 1];
                for (int i = 0; i < cateNames.length; i++) {
                    cateNameInts[i] = Integer.parseInt(cateNames[i]);
                }
                List<Integer> cateIds = Arrays.asList(cateNameInts);
                Set<Integer> cateIdSet = new HashSet<>(cateIds);
                cateIds = new ArrayList<>(cateIdSet);
                map.put("cateName",vedioCategoryDao.getCateNameById(cateIds));
            }
            map.put("filePath",upyunProperties.getDomain() + map.get("filePath"));
            map.put("logoPath",upyunProperties.getDomain() + map.get("logoPath"));
            if(StringUtils.isNotBlank((String) map.get("ageType"))) {
                String[] ageTypeStr = ((String) map.get("ageType")).split(",");
                String ageType = getAgeTypeNames(ageTypeStr);
                map.put("ageType",ageType);
            }
            result.add(map);
        }
        page.setRecords((List<VedioDetail>) new VedioWarpper(result).warp());
        return super.packForBT(page);
    }

    /**
     * 删除关联关系
     * @param channelResIds
     * @return
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object deleteVedio(@RequestParam(value = "channelResIds") String channelResIds) {
        String[] channelResIdArr = channelResIds.split(",");
        List<Integer> channelResIdList = new ArrayList<>();
        for (String channelResId : channelResIdArr) {
            channelResIdList.add(Integer.valueOf(channelResId));
        }
        //删除关联关系
        channelItemMapper.deleteBatchIds(channelResIdList);
        return super.SUCCESS_TIP;
    }

    /**
     * 新增页面
     * @param model
     * @return
     */
    @RequestMapping(value = "/addPage")
    public String addPage(Model model) {
        List<Channel> channelList = channelMapper.selectList(new EntityWrapper<>());
        List<Map<String,Object>> resultList = new ArrayList<>();
        for (Channel channel : channelList) {
            Map<String,Object> map = new HashMap<>(4);
            map.put("id",channel.getId());
            map.put("title",channel.getTitle());
            resultList.add(map);
        }
        model.addAttribute("channelList",resultList);
        return PREFIX + "channel_item_add.html";
    }

    /**
     * 音频列表
     * @param keyword
     * @return
     */
    @RequestMapping(value = "/radio/list")
    @ResponseBody
    public Object radioList(@RequestParam(value = "keyword",required = false) String keyword) {
        List<Map<String,Object>> radioList = vedioDetailDao.getRadioByKeywords(keyword,0);
        return radioList;
    }

    /**
     * 新增关联关系
     * @param channelRadioDto
     * @return
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(ChannelRadioDto channelRadioDto) {
        if(ToolUtil.isOneEmpty(channelRadioDto,channelRadioDto.getChannels(),channelRadioDto.getRadios())) {
            throw new BussinessException( BizExceptionEnum.REQUEST_NULL);
        }
        String radios = channelRadioDto.getRadios();
        String[] radioIdArr = radios.split(",");
        List<Integer> radioIdList = new ArrayList<>();
        for (String radioId : radioIdArr) {
            radioIdList.add(Integer.parseInt(radioId));
        }
        for (Integer radioId : radioIdList) {
            ChannelItem channelItem = new ChannelItem();
            channelItem.setChannelId(channelRadioDto.getChannels());
            channelItem.setResourceId(radioId);
            channelItemMapper.insert(channelItem);
        }
        return SUCCESS_TIP;
    }

    /**
     * 年龄段判断
     * @param ageTypeIds
     * @return
     */
    private String getAgeTypeNames(String[] ageTypeIds) {
        String ageType = "";
        for (int i = 0; i < ageTypeIds.length; i++) {
            Integer ageTypeInt = Integer.parseInt(ageTypeIds[i]);
            if(ageTypeInt == -1) {
                if(StringUtils.isBlank(ageType)) {
                    ageType = "所有";
                } else {
                    ageType += ",所有";
                }
            }
            if(ageTypeInt == 0) {
                if(StringUtils.isBlank(ageType)) {
                    ageType = "胎教";
                } else {
                    ageType += ",胎教";
                }
            }
            if(ageTypeInt == 1) {
                if(StringUtils.isBlank(ageType)) {
                    ageType = "0~1岁";
                } else {
                    ageType += ",0~1岁";
                }
            }
            if(ageTypeInt == 2) {
                if(StringUtils.isBlank(ageType)) {
                    ageType = "1~3岁";
                } else {
                    ageType += ",1~3岁";
                }
            }
            if(ageTypeInt == 3) {
                if(StringUtils.isBlank(ageType)) {
                    ageType = "3~5岁";
                } else {
                    ageType += ",3~5岁";
                }
            }
            if(ageTypeInt == 4) {
                if(StringUtils.isBlank(ageType)) {
                    ageType = "5~7岁";
                } else {
                    ageType += ",5~7岁";
                }
            }
            if(ageTypeInt == 5) {
                if(StringUtils.isNotBlank(ageType)) {
                    ageType += ",7~12岁";
                } else {
                    ageType = "7~12岁";
                }
            }
        }
        return ageType;
    }
}
